package com.x.attendance.assemble.control.service;

import java.util.List;
import java.util.concurrent.CompletableFuture;

import com.x.attendance.core.entity.AttendanceDevice;
import com.x.base.core.container.EntityManagerContainer;
import com.x.base.core.container.factory.EntityManagerContainerFactory;
import com.x.base.core.project.logger.Logger;
import com.x.base.core.project.logger.LoggerFactory;

/**
 * 设备同步服务
 * @author Manus AI
 */
public class DeviceSyncService {

	private static Logger logger = LoggerFactory.getLogger(DeviceSyncService.class);
	
	private AttendanceDeviceService deviceService;

	public DeviceSyncService() {
		this.deviceService = new AttendanceDeviceService();
	}

	/**
	 * 同步指纹到所有启用的设备
	 */
	public void syncFingerprintToDevices(String employeeId, byte[] template) {
		try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
			List<AttendanceDevice> devices = getEnabledDevices(emc);
			
			for (AttendanceDevice device : devices) {
				CompletableFuture.runAsync(() -> {
					try {
						syncFingerprintToDevice(device, employeeId, template);
					} catch (Exception e) {
						logger.error(e);
					}
				});
			}
		} catch (Exception e) {
			logger.error(e);
		}
	}

	/**
	 * 同步指纹到指定设备
	 */
	public boolean syncFingerprintToDevice(AttendanceDevice device, String employeeId, byte[] template) {
		try {
			// 连接设备
			boolean connected = deviceService.connectDevice(device.getIpAddress(), device.getPort());
			if (!connected) {
				logger.error("连接设备失败: " + device.getName());
				return false;
			}

			// 上传指纹模板
			boolean uploaded = deviceService.uploadFingerprint(employeeId, template);
			if (uploaded) {
				logger.info("指纹同步成功: 设备={}, 员工={}", device.getName(), employeeId);
			} else {
				logger.error("指纹同步失败: 设备={}, 员工={}", device.getName(), employeeId);
			}

			// 断开连接
			deviceService.disconnect();
			
			return uploaded;
		} catch (Exception e) {
			logger.error(e);
			return false;
		}
	}

	/**
	 * 同步员工照片到设备
	 */
	public void syncPhotoToDevices(String employeeId, byte[] photo) {
		try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
			List<AttendanceDevice> devices = getEnabledDevices(emc);
			
			for (AttendanceDevice device : devices) {
				CompletableFuture.runAsync(() -> {
					try {
						syncPhotoToDevice(device, employeeId, photo);
					} catch (Exception e) {
						logger.error(e);
					}
				});
			}
		} catch (Exception e) {
			logger.error(e);
		}
	}

	/**
	 * 同步照片到指定设备
	 */
	public boolean syncPhotoToDevice(AttendanceDevice device, String employeeId, byte[] photo) {
		try {
			// 连接设备
			boolean connected = deviceService.connectDevice(device.getIpAddress(), device.getPort());
			if (!connected) {
				logger.error("连接设备失败: " + device.getName());
				return false;
			}

			// 上传照片
			boolean uploaded = deviceService.uploadPhoto(employeeId, photo);
			if (uploaded) {
				logger.info("照片同步成功: 设备={}, 员工={}", device.getName(), employeeId);
			} else {
				logger.error("照片同步失败: 设备={}, 员工={}", device.getName(), employeeId);
			}

			// 断开连接
			deviceService.disconnect();
			
			return uploaded;
		} catch (Exception e) {
			logger.error(e);
			return false;
		}
	}

	/**
	 * 获取启用的设备列表
	 */
	private List<AttendanceDevice> getEnabledDevices(EntityManagerContainer emc) throws Exception {
		return emc.listEqual(AttendanceDevice.class, AttendanceDevice.enabled_FIELDNAME, true);
	}

	/**
	 * 重启设备
	 */
	public boolean restartDevice(AttendanceDevice device) {
		try {
			boolean connected = deviceService.connectDevice(device.getIpAddress(), device.getPort());
			if (!connected) {
				logger.error("连接设备失败: " + device.getName());
				return false;
			}

			boolean restarted = deviceService.restartDevice();
			deviceService.disconnect();
			
			if (restarted) {
				logger.info("设备重启成功: " + device.getName());
			} else {
				logger.error("设备重启失败: " + device.getName());
			}
			
			return restarted;
		} catch (Exception e) {
			logger.error(e);
			return false;
		}
	}

	/**
	 * 测试设备连接
	 */
	public boolean testDeviceConnection(AttendanceDevice device) {
		try {
			boolean connected = deviceService.connectDevice(device.getIpAddress(), device.getPort());
			if (connected) {
				deviceService.disconnect();
				return true;
			}
			return false;
		} catch (Exception e) {
			logger.error(e);
			return false;
		}
	}
}

